package com.zecan.blog.security.handler;

import cn.hutool.json.JSONUtil;
import com.zecan.blog.common.BlogResult;
import com.zecan.blog.common.status.UserStatus;
import com.zecan.blog.utils.BlogResultUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName JwtAccessDeniedHandler
 * @Description
 * @date 2022/10/29 20:41
 * @Version 1.0
 * 用户访问页面权限不足处理器
 */
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        // 设置状态为 没有权限403
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);

        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(JSONUtil.toJsonStr(BlogResultUtils.userStatus(UserStatus.USER_NOT_AUTHORITY)).getBytes(StandardCharsets.UTF_8));

        outputStream.flush();
        outputStream.close();
    }
}
